/**
 * 蜗牛速配员工端 - App
 * http://menger.me
 * @大梦
 */

'use strict';

import React, {useState, useEffect} from 'react'
import {
    View,
    Text,
    Linking,
    AppState,
    Platform,
    StyleSheet,
    BackHandler,
    ToastAndroid,
    NativeModules,
    DeviceEventEmitter,
    TouchableHighlight,
} from 'react-native'
import RouterContainer from '../routers/RouterContainer';
import SplashScreen from 'react-native-splash-screen';
import * as WeChat from 'react-native-wechat-lib';
import JShareModule from 'jshare-react-native';
import XPay from 'react-native-puti-pay';
import JPush from 'jpush-react-native';

import { BaiduMapManager } from 'react-native-baidu-map';
import {inject, observer} from 'mobx-react';

// 百度地图初始化
BaiduMapManager.initSDK('dqgGuAMM5mEiQOFhzeW5fNyziFPQ89fR');

@inject('loginStore')
@observer
export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            article: [],
        }
    }

    _onPressToNavigate = (pageTitle, component, params) => {
        AlertManager.hide();
        RouterHelper.navigate(pageTitle, component, {
            ...params,
            onCallBack: () => this._showPrivacyPolicy(),
        });
    };

    componentDidMount() {
        // 初始化设置，先调用
        this._initSetting();
        // 检查系统版本
        this._checkVersion();
        // 获取当前位置
        this._getCurrentPosition();
        // 处理登陆状态
        this._handleLoginState();
        // 通知,先调用
        // this._addPushListener();
        // 检查用户的JPush
        // this._setAlias();
    };

    // 初始化设置
    _initSetting = () => {
        if (__IOS__) {
            // 启动极光分享 ios需要
            JShareModule.setup()
        }
        // 微信的lib（ios上架兼容）
        WeChat.registerApp(Constants.WECHAT_APPID, 'http://huyun.yichi.3todo.com');
        // debug模式
        JShareModule.setDebug({enable: __DEV__});
        //设置微信ID
        // XPay.setWxId(Constants.WECHAT_APPID);
        //设置支付宝URL Schemes
        XPay.setAlipayScheme(Constants.ALIPAY_SCHME);
        // 显示竖屏
        // Orientation.lockToPortrait()
    };

    // 检查系统版本
    _checkVersion = async () => {
        // UpdateManager.checkForUpdate();
        CheckVersion(false, false, (result) => {
            console.log('版本result------------->', result)
        });
    };

    // 获取当前位置
    _getCurrentPosition = async () => {
        let {loginStore} = this.props;
        let _locationInfo = await loginStore.getCurrentPosition();
        console.log('_locationInfo---->', _locationInfo);
    };

    // 处理登陆状态
    _handleLoginState = async () => {
        const firstOpen = await StorageManager.load(Constants.FIRST_OPEN);
        const showPrivacyPolicy = await StorageManager.load(Constants.SHOW_PRIVACY_POLICY);
        const localRes = await StorageManager.load(Constants.USER_INFO_KEY);
        console.log('showPrivacyPolicy---->', showPrivacyPolicy);
        if (showPrivacyPolicy.code !== StatusCode.SUCCESS_CODE) {
            this._requestPrivacyPolicy();
        }
        if (firstOpen.code === StatusCode.SUCCESS_CODE && !firstOpen.data) {
            if (localRes.code === StatusCode.SUCCESS_CODE && localRes.data) {
                if (localRes.data.token === undefined || localRes.data.token === '') {
                    // 未登录
                    this.timer1 = setTimeout(() => {
                        RouterHelper.reset('', 'Tab');
                        SplashScreen.hide();
                    }, 1000);
                } else {
                    // 已经登录
                    global.token = localRes.data.token;
                    this._checkTokenStatus(localRes);
                }
            } else {
                this.timer2 = setTimeout(() => {
                    RouterHelper.reset('', 'Tab');
                    SplashScreen.hide();
                }, 1000);
            }
        } else {
            // 第一次安装app
            this.timer3 = setTimeout(() => {
                RouterHelper.reset('', 'Tab');
                SplashScreen.hide();
            }, 1000);
        }
    };

    _checkTokenStatus = async (localRes) => {
        let {loginStore} = this.props;
        try {
            let result = await loginStore.getLatestUserInfo();
            if (result) {
                if (result.code === StatusCode.SUCCESS_CODE) { // 成功
                    if (result.data.type == 2 || result.data.type == 1) {
                        let alias = Constants.ALIAS_CARRIER + result.data.id;
                        loginStore.setAlias(alias)
                        this.timer4_1 = setTimeout(() => {
                            RouterHelper.reset('', 'Tab');
                        }, 10);
                    } else {
                        let alias = Constants.ALIAS_DRIVER + result.data.id;
                        loginStore.setAlias(alias)
                        this.timer4_1 = setTimeout(() => {
                            RouterHelper.reset('', 'DriverOrder');
                        }, 10);
                    }
                } else if (result.code === StatusCode.TOKEN_EXPIRED_CODE) { // token过期4003
                    this.timer5_1 = setTimeout(() => {
                        RouterHelper.navigate('', 'Tab');
                    }, 10);
                }
                this.timer4_2 = setTimeout(() => {
                    SplashScreen.hide();
                }, 500);
            } else {
                SplashScreen.hide();
            }
        } catch (e) {
            SplashScreen.hide();
        }
    };

    // 隐私政策弹窗
    _requestPrivacyPolicy = async () => {
        let url = ServicesApi.ARTICLE_ARTICLE_LIST;
        let data = {};
        const result = await Services.post(url, data);
        console.log('result---->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                article: result.data,
            }, () => this._showPrivacyPolicy());
        }
    };

    _showPrivacyPolicy = async () => {
        let {article, mobile} = this.state;
        let detail = (
            <View style={styles.messageView}>
                <Text style={styles.messageText}>
                    感谢您下载并使用《易驰运输承运端》,为向您提供更好的服务，可能会收集您的个人信息。我们将根据您的意愿和相关法律，严格保管并审慎使用这些信息。请您在使用前点击阅读
                    <Text
                        style={[styles.powerbyItemCur]}
                        onPress={() => this._onPressToNavigate(article[3].title, 'WebPage', {uri: article[3].url})}
                    >{article[3].title}</Text>
                    <Text style={[styles.powerbyItemCur]}>及</Text>
                    <Text
                        style={[styles.powerbyItem, styles.powerbyItemCur]}
                        onPress={() => this._onPressToNavigate(article[0].title, 'WebPage', {uri: article[0].url})}
                    >{article[0].title}</Text>
                    如果同意，请点击下方“同意”按钮开启使用《易驰运输承运端》。阅读过程中，如有疑问，可联系我们的客服热线咨询
                    <Text style={styles.textStyle} onPress={() => this._onMakeCall(mobile)}>{mobile}</Text>
                </Text>
            </View>
        );
        let params = {
            detail,
            title: '温馨提示',
            option: {
                modal: true,
            },
            actions: [
                { title: '不同意', onPress: () => ExitAppManager.exitApp()},
                {
                    title: '同意',
                    titleStyle: styles.powerbyItemCur,
                    onPress: () => {
                        StorageManager.save(Constants.SHOW_PRIVACY_POLICY, false);
                        AlertManager.hide();
                    },
                },
            ]
        };
        AlertManager.show(params);
    };
 
    _addPushListener = () => {
        JPush.init();
        // 连接状态
        this.connectListener = result => {
            console.log("connectListener:" + JSON.stringify(result))
        };
        JPush.addConnectEventListener(this.connectListener);
        // 通知回调
        this.notificationListener = result => {
            console.log("notificationListener:" + JSON.stringify(result))
        };
        JPush.addNotificationListener(this.notificationListener);
        // 本地通知回调
        this.localNotificationListener = result => {
            console.log("localNotificationListener:" + JSON.stringify(result))
        };
        JPush.addLocalNotificationListener(this.localNotificationListener);
        // 自定义消息回调
        this.customMessageListener = result => {
            console.log("customMessageListener:" + JSON.stringify(result))
        };
        JPush.addCustomMessagegListener(this.customMessageListener);
        // tag alias事件回调
        this.tagAliasListener = result => {
            console.log("tagAliasListener:" + JSON.stringify(result))
        };
        JPush.addTagAliasListener(this.tagAliasListener);
        // 手机号码事件回调
        this.mobileNumberListener = result => {
            console.log("mobileNumberListener:" + JSON.stringify(result))
        };
        JPush.addMobileNumberListener(this.mobileNumberListener);
    };

    // 设置别名
    _setAlias = async () => {
        JPush.queryAlias({"sequence":1})
    };

    _clearTimeout = () => {
        let times = [this.timer1, this.timer2, this.timer3, this.timer4_1, this.timer4_2];
        ClearTimer(times);
    };

    render() {
        return (
            <RouterContainer />
        );
    }
}

const styles = StyleSheet.create({
    messageView: {
        marginTop: 15,
        paddingVertical: 10,
        textAlign: 'justify',
        paddingHorizontal: 15,
    },
    messageText: {
        fontSize: 13,
        color: '#666',
        lineHeight: 18,
        textAlign: 'justify',
    },
    powerbyItemCur: {
        color: '#539ff3',
    },
});